package controller

import (
	"kandy/app/service"
	"kandy/framework"
	"kandy/utils"
	"net/http"
)

type UserController struct {
}

func (this *UserController) Router(router *framework.RouterHandler) {
	prefix := "/user"
	router.Router(prefix+"/register", this.register)
	router.Router(prefix+"/login", this.login)
	router.Router(prefix+"/find_all", this.findAll)
}

func (this *UserController) register(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")

	if utils.Empty(username) || utils.Empty(password) {
		utils.ResultFail(w, "用户名或密码错误")
		return
	}
	id := new(service.UserService).Insert(username, password)
	if id > 0 {
		utils.ResultOK(w, "注册成功")
	} else {
		utils.ResultFail(w, "注册失败")
	}
}

func (this *UserController) login(w http.ResponseWriter, r *http.Request) {
	username := r.FormValue("username")
	password := r.FormValue("password")

	if utils.Empty(username) || utils.Empty(password) {
		utils.ResultFail(w, "用户名或密码错误")
		return
	}

	users := new(service.UserService).SelectUserByName(username)
	if len(users) > 0 {
		if users[0].Password == password {
			utils.ResultOK(w, "登录成功")
		} else {
			utils.ResultFail(w, "密码错误")
		}
	} else {
		utils.ResultFail(w, "没有数据")
	}
}

func (this *UserController) findAll(w http.ResponseWriter, r *http.Request) {
	users := new(service.UserService).SelectAllUser()
	utils.ResultJsonOk(w, users)
}
